﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AuthenticationCenter.Service
{
    /// <summary>
    /// 对称可逆加密
    /// </summary>
    public class HsJwtService : IJwtService
    {
        private readonly JwtTokenOptions _jwtTokenOptions;
        public HsJwtService(IOptions<JwtTokenOptions> jwtTokenOptions)
        {
            _jwtTokenOptions = jwtTokenOptions.Value;
        }

        public string GetToken(string name, string password)
        {
            // 有效载荷，尽量避免敏感信息
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, name),
                new Claim("NickName", name),
                new Claim(ClaimTypes.Role, "Admin"),
                new Claim("CustomField", "CustomValue"),
            };

            // 需要加密：需要加密key
            // nuget 引入：Microsoft.IdentityModel.Tokens

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOptions.SecurityKey));

            SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // nuget 引入：System.IdentityModel.Tokens.Jwt
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: _jwtTokenOptions.Issuer,
                audience: _jwtTokenOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: credentials
                );

            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;
        }
    }
}
